package com.atguigu.gulimall.member.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ：TJH
 * @date ：Created in 2020/7/4 20:40
 * @description：
 */
@Configuration
public class GuliFeignConfig {

    /**
     * feign拦截器
     *
     * @return
     */
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        //feign远程之前先进行RequestInterceptor.apply
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                //1、ReqeustContextHolder拿到刚进来的这个请求,老请求
                ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (servletRequestAttributes != null) {
                    HttpServletRequest request = servletRequestAttributes.getRequest();
                    //同步请求头数据cookie
                    String cookie = request.getHeader("Cookie");
                    //给新请求带上老请求的cookie
                    template.header("Cookie", cookie);
                }
            }
        };
    }
}
